package com.fer.tankr;

import android.app.Activity;
import android.provider.Settings;
import android.provider.Settings.System;

import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;


public class GlobalState {
	
	public static String HIGH_SCORE = "highScore";
	public static String USER_ID = "userId";
	public static String DISPLAY_NAME = "displayName";
	public static String MAX_LEVEL = "currentLevel";
	public static String CLASS_NAME = "ScoreData";
	
	private static GlobalState instance;
	
	private ParseObject scoreData;
	private int currentLevel;
	private static String id; 
	
	private GlobalState() {
		if (scoreData == null)
		{
			scoreData = new ParseObject(CLASS_NAME);
			setCurrentLevel(1);
			setMaxLevel(1);
		}
	};
	
	public static GlobalState get()
	{
		if (instance == null)
		{
			instance = new GlobalState();
		}
		return instance;
	}
	
	public void setUser(ParseUser user)
	{
		this.scoreData = user;
	}
	
	public ParseObject getUser()
	{
		return scoreData;
	}
	
	public void setHighScore(int score)
	{
		scoreData.put(HIGH_SCORE, score);
	}
	
	public int getMaxLevel()
	{
		Integer num =  scoreData.getInt(MAX_LEVEL);
		if (num!=null)
		{
			return num;
		}
		else return 1;
	}
	
	public void setMaxLevel(int level)
	{
		if (getMaxLevel()< level)
		{
			scoreData.put(MAX_LEVEL, level);
			try {
				scoreData.saveInBackground();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public int getCurrentLevel()
	{
		return currentLevel;
	}
	
	public void setCurrentLevel(int level)
	{
		currentLevel = level;
	}

	public void init(Activity activity) {
		id = System.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
		ParseQuery query = new ParseQuery(CLASS_NAME);
		query.whereMatches(USER_ID, id).getFirstInBackground(getCallback());
		
	}

	private GetCallback getCallback() {
		return new GetCallback() {
			
			@Override
			public void done(ParseObject obj, ParseException arg1) {
				java.lang.System.out.println(obj);
				scoreData = obj;
				if (scoreData == null)
				{
					scoreData = new ParseObject(CLASS_NAME);
					setId(id);
					setCurrentLevel(1);
					setMaxLevel(1);
				}
				else
				{
					scoreData = obj;
				}
			}

			
		};
	}
	private void setId(String id) {
		scoreData.put(USER_ID, id);
	}
}
